package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    // @Autowired
    // private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    /*拿到key  value输出的地址*/
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmealId);
                map.put("checkgroup_id", checkgroupId);
                /*再添加中间表*/
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
        savePic2Redis(setmeal.getImg());

        /*当添加套餐后生成静态页面*/
        //  generateMobileStaticHtml();

        List<Setmeal> setmealList = setmealDao.findAll();
        /*套餐列表*/
        generateMobileStaticListHtml(setmealList);

        /*套餐详情
         * 传id
         * */
        generateMobileStaticDetailHtml(setmealId);
    }

    /*生成方法静态页面*/

    public void generateMobileStaticListHtml(List<Setmeal> setmealList) {
        Map map = new HashMap();
        map.put("setmealList", setmealList);
        /*模板名  html的名字 文件名ftl*/
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);

    }

    /*一个套餐可能有多个套餐详情*/
    public void generateMobileStaticDetailHtml(int setmealId) {
        Map map = new HashMap();
        map.put("setmeal", setmealDao.findByID(setmealId));
        generateHtml("mobile_setmeal_detail.ftl",
                "setmeal_detail_" + setmealId + ".html", map);
    }

    /*生成通用方法静态页面
     * 模板名  html的名字 文件名ftl
     * */
    public void generateHtml(String teplateName, String htmlPageName, Map map) {
        /*获得配置对象*/
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(teplateName);
            /*输出位置目录+新名字*/
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            template.process(map, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        String queryString1 = queryPageBean.getQueryString1();
        PageHelper.startPage(currentPage, pageSize);

        Page<Setmeal> page = setmealDao.selectByCondition(queryString, queryString1);
        long total = page.getTotal();
        List<Setmeal> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findByID(id);
    }

    @Override
    public void power(int id, Boolean open) {
        /*根据Id修改*/
        setmealDao.updateOpen(id, open);
        /*判断*/
        Setmeal setmeal = setmealDao.findByOpen(id);
        List<Setmeal> setmealList = setmealDao.findAll();

        if (setmeal.isOpen()) {
            System.out.println(111);
            /*套餐列表*/
            generateMobileStaticListHtml(setmealList);
            /*套餐详情
             * 传id
             * */
            generateMobileStaticDetailHtml(id);
            /*更新*/
        } else {
            /*删除*/
            generateMobileStaticListHtml(setmealList);
            try {
                File file = new File("D:\\Project\\project02\\health_parent\\health_mobile\\src\\main\\webapp\\pages\\setmeal_detail_" + id + ".html");
                if (file.exists()) {
                    FileInputStream inputStream = new FileInputStream(file);
                    inputStream.close();
                    boolean flag = file.delete();
                    System.out.println(flag);
                }
            } catch (Exception e) {
                System.out.println(e);
                System.out.println(222);
            }
        }

    }

    private void savePic2Redis(String pic) {
        //jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }
}
